package com.lyl.momanapp.util.utlis;

import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.iflytek.cloud.SpeechUtility;
import com.jude.utils.JUtils;
import com.lljjcoder.city_20170724.CityPickerView;
import com.lyl.momanapp.R;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.stx.xhb.xbanner.XBanner;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 名字 梁亚龙
 * 时间 2017/8/15.
 * QQ邮箱 503934353@qq.com
 */

public class MyUtils extends Application {
    public static MyUtils INSTANCE;
    public String mAppDir;
    public String mPicturesDir;
    public String mFilesDir;
    public String mExternalDir;

    @Override
    public void onCreate() {
        super.onCreate();
        x.Ext.init(this);
        x.Ext.setDebug(true);
        INSTANCE = this;
        initAppDir();

        /**
         * 科大讯飞配置
         */
        SpeechUtility.createUtility(this, "appid=" + "59633429");
        JUtils.initialize(this);


        initImageLoader(this);

        /**
         * 初始化下载服务
         */
        //startService(new Intent(this, DownLoadService.class));
    }


    /**
     * 配置ImageLoder
     */
    public static void initImageLoader(Context context) {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showStubImage(R.drawable.white_bg) // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.white_bg) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.white_bg) // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true) // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true) // 设置下载的图片是否缓存在SD卡中
                // .displayer(new RoundedBitmapDisplayer(20)) // 设置成圆角图片
                .build(); // 创建配置过得DisplayImageOption对象

        File cacheDir = StorageUtils.getCacheDirectory(context); // 缓存文件夹路径
        // This configuration tuning is custom. You can tune every option, you
        // may tune some of them,
        // or you can create default configuration by
        // ImageLoaderConfiguration.createDefault(this);
        // method.
        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(
                context);
        config.threadPriority(Thread.NORM_PRIORITY - 2);
        config.denyCacheImageMultipleSizesInMemory();
        config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
        config.memoryCacheSize(50 * 1024 * 1024);
        config.diskCacheSize(200 * 1024 * 1024); // 50 MiB
        config.tasksProcessingOrder(QueueProcessingType.LIFO);
        config.memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)); // 可以通过自己的内存缓存实现
        config.diskCache(new UnlimitedDiskCache(cacheDir)); // default 可以自定义缓存路径
        config.diskCacheFileCount(100); // 可以缓存的文件数量
        config.defaultDisplayImageOptions(options);
        config.writeDebugLogs(); // Remove for release app
        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config.build());
    }


    public String getTime() {
        long time = System.currentTimeMillis();//获取系统时间的10位的时间戳
        String str = String.valueOf(time);
        return str;
    }

    public void xUutlisImg(String url, String finished, final Handler handler, final int id) {
        RequestParams params = new RequestParams(url);
        params.setMultipart(true);
        params.addBodyParameter("image", new File(finished));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                //解析result
                Message message = new Message();
                message.what = id;
                message.obj = result.toString();
                handler.sendMessage(message);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }

    /**
     * @param url     URl地址
     * @param map     键值对map集合
     * @param handler
     * @param id
     */
    public void xUtilsPost(String url, HashMap<String, String> map, final Handler handler, final int id) {
        final RequestParams params = new RequestParams(url);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            params.addQueryStringParameter(key, map.get(key));
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                //解析result
                Message message = new Message();
                message.what = id;
                message.obj = result.toString();
                handler.sendMessage(message);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });

    }

    /**
     * @param url     URl地址
     * @param map     键值对map集合
     * @param handler
     * @param id
     */
    public void xUtilsGet(String url, HashMap<String, String> map, final Handler handler, final int id) {
        final RequestParams params = new RequestParams(url);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            params.addQueryStringParameter(key, map.get(key));
        }
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                //解析result
                Message message = new Message();
                message.what = id;
                message.obj = result.toString();
                handler.sendMessage(message);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });

    }

    /**
     * 验证手机号
     *
     * @param mobiles 手机号
     * @return
     */
    public static boolean isMobileNO(String mobiles) {

        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");

        Matcher m = p.matcher(mobiles);

        System.out.println(m.matches() + "---");

        return m.matches();

    }

    /**
     * 这是XBanner 的URL图片加载方法
     * 需要导入compile 'com.android.support:design:26.0.0-alpha1'
     *
     * @param mBannerNet XBanner
     * @param imgesUrl   轮播图的URL
     */
    public void xbanner(XBanner mBannerNet, final List<String> imgesUrl) {

        mBannerNet.setData(imgesUrl, null);//第二个参数为提示文字资源集合
        mBannerNet.setmAdapter(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                x.image().bind((ImageView) view, imgesUrl.get(position));
            }
        });
    }

    /**
     * 这是提示对话框，是用来提示保存信息的方法
     * 有确定和取消两个按钮
     *
     * @param context  上下文
     * @param title    标题
     * @param Message  提示信息
     * @param state    状态码 ture带有取消按钮
     * @param callback 接口
     */
    public void alertDialogPrompt(Context context, String title, String Message, boolean state, final InterfaceUtils.PromptCallback callback) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(title);
        builder.setMessage(Message);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                callback.onPositiveButton();
            }
        });
        if (state) {
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    callback.onNegativeButton();
                }
            });
        }
        builder.show();

    }

    /**
     * 这是输入验证码框
     *
     * @param context
     * @param title
     * @param editCallback
     */
    public void alertDialogEdit(Context context, String title, final InterfaceUtils.EditCallback editCallback) {
        final EditText inputServer = new EditText(context);
        inputServer.setInputType(InputType.TYPE_CLASS_NUMBER);
        inputServer.setMaxLines(6);

        AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(title).setView(inputServer)
                .setNegativeButton("取消", null);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                editCallback.onPositiveButton(inputServer);

            }
        });
        builder.show();
    }

    /**
     * 这是个单选框
     *
     * @param context       上下文
     * @param title         标题
     * @param data          数据
     * @param radioCallback 接口回调选择项
     */
    public void alertDialogRadio(Context context, String title, final String[] data, final InterfaceUtils.RadioCallback radioCallback) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(title);
        builder.setItems(data, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                radioCallback.onPositiveButton(i, data);
                builder.create();
            }
        });
        builder.show();

    }

    /**
     * 生成视图的预览
     *
     * @param v
     * @return 视图生成失败返回null
     * 视图生成成功返回视图的绝对路径
     */
    public String saveImage(RelativeLayout v, String picName, Context context) {
        v.setDrawingCacheEnabled(true);
        Bitmap tBitmap = v.getDrawingCache();
        // 拷贝图片，否则在setDrawingCacheEnabled(false)以后该图片会被释放掉
        tBitmap = tBitmap.createBitmap(tBitmap);
        v.setDrawingCacheEnabled(false);
        if (tBitmap != null) {
            return saveBitmap(tBitmap, picName, context);
        } else {
            return saveBitmap(tBitmap, picName, context);
        }
    }

    public String saveBitmap(Bitmap bm, String picName, Context context) {
        Log.e("11", "保存图片");
        String picName1 = picName + ".jpg";
        File f = new File(context.getFilesDir() + "/" + picName1);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            Log.i("11", "已经保存");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            return f.getPath();
        }

    }

    /**
     * 这是一个城市选择器 需要导入
     * compile 'liji.library.dev:citypickerview:2.0.1'
     * 需要 show出来
     *
     * @param context 上下文
     * @return
     */
    public CityPickerView cityPickerView(Context context) {
        CityPickerView cityPicker = new CityPickerView.Builder(context)
                .textSize(20)
                .title("地址选择")
                .backgroundPop(0xa0000000)
                .titleBackgroundColor("#FFFFD447")
                .titleTextColor("#000000")
                .backgroundPop(0xa0000000)
                .confirTextColor("#000000")
                .cancelTextColor("#000000")
                .province("江苏省")
                .city("常州市")
                .district("天宁区")
                .textColor(Color.parseColor("#000000"))
                .provinceCyclic(true)
                .cityCyclic(false)
                .districtCyclic(false)
                .visibleItemsCount(7)
                .itemPadding(10)
                .onlyShowProvinceAndCity(false)
                .build();
        return cityPicker;
    }

    private static Toast mToast;

    public static void showToast(Context context, int resId, int duration) {
        showToast(context, context.getString(resId), duration);
    }

    public static void showToast(Context context, String msg, int duration) {
        if (mToast == null) {
            mToast = Toast.makeText(context, msg, duration);
        } else {
            mToast.setText(msg);
        }
        mToast.show();
    }

    public static MyUtils getInstance() {
        return INSTANCE;
    }

    private void initAppDir() {
        File file = getExternalFilesDir(null);
        if (!file.exists()) {
            file.mkdirs();
        }

        mAppDir = file.getAbsolutePath();

        file = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (!file.exists()) {
            file.mkdirs();
        }

        mPicturesDir = file.getAbsolutePath();

        file = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
        if (!file.exists()) {
            file.mkdirs();
        }

        mFilesDir = file.getAbsolutePath();

        file = Environment.getExternalStorageDirectory();
        mExternalDir = file.getAbsolutePath();
    }
}

